package fr.demos.cinepantin.controleur;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.demos.cinepantin.dao.impl.UploadImage;
import fr.demos.cinepantin.dao.interfac.UploadInterface;
import fr.demos.cinepantin.exception.UploadImageExceptions;
import fr.demos.cinepantin.exception.UploadImageMauvaisFormatExceptions;
import fr.demos.cinepantin.util.Configuration;

/**
 * @author CQP-DNT
 * Servlet implementation class TestUpload
 */
@WebServlet("/TestUpload")
public class TestUpload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public TestUpload() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("page", "/testUpload.jsp");
		RequestDispatcher rd = request.getRequestDispatcher("/page.jsp");
		rd.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// On récupére l'action
		String action = request.getParameter("action");

		if (action.equals("uploadImage")) {
			UploadInterface uploadImage = new UploadImage();
			List<String> listFilesNames;
			try {
				listFilesNames = uploadImage.UploadFile(request);

				for (String fileName : listFilesNames) {
					System.out.println(Configuration.getAbsolutePathDossierUploadImage(request) + fileName);
					request.setAttribute("srcImage", Configuration.DOSSIER_UPLOAD_IMAGE + fileName);
				}
			} catch (UploadImageMauvaisFormatExceptions e) {
				System.out.println("problème upload image");
				request.setAttribute("erreurImage", "le format de l'image n'est pas reconnu");

			} catch (UploadImageExceptions e) {
				request.setAttribute("erreurImage", "Un problème est survenu durant l'upload de l'images");
				// Impossible d'enregistrer l'image
				e.printStackTrace();
			}
			request.setAttribute("page", "/testUpload.jsp");
			RequestDispatcher rd = request.getRequestDispatcher("/page.jsp");
			rd.forward(request, response);
		}

	}
}
